package com.loan.market.ui

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.widget.LinearLayout.LayoutParams
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.view.isInvisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import coil.load
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.loan.market.R
import com.loan.market.base.BaseBindingFragment
import com.loan.market.bean.Recommend
import com.loan.market.bean.Type
import com.loan.market.bean.UserInfo
import com.loan.market.databinding.FragmentHomeBinding
import com.loan.market.event.LoginEvent
import com.loan.market.event.LogoutEvent
import com.loan.market.event.SaveInfoEvent
import com.loan.market.http.ApiService
import com.loan.market.http.getHttpMap
import com.loan.market.http.request
import com.loan.market.util.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs

class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(), OnClickListener {

    override fun getViewBinding(): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(layoutInflater)
    }


    private var selectType = 0
    private val types = arrayListOf<Type>()

    private val typeAdapter by lazy {
        object : BaseQuickAdapter<Type, QuickViewHolder>() {
            override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: Type?) {
                val tvType = holder.getView<TextView>(R.id.tv_type)
                tvType.text = item?.category
                tvType.isSelected = position == selectType
                tvType.updateLayoutParams<LayoutParams> { width = itemWidth }
                if (position == selectType) {
                    tvType.textSize = 14f
                } else {
                    tvType.textSize = 12f
                }
            }

            override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
                return QuickViewHolder(R.layout.item_type, parent)
            }
        }
    }

    private var scrollHeight = 0
    private var itemWidth = 0

    override fun initUi() {
        EventBus.getDefault().register(this)
        binding.clApply.post { scrollHeight = binding.clApply.height + 54f.dp2px() }
        binding.rvType.post {
            itemWidth = (binding.rvType.width - 44f.dp2px()) / 4
            binding.rvType.adapter = typeAdapter
        }
        binding.flTop.updateLayoutParams<LayoutParams> { topMargin = requireContext().getStatusBarHeight() }
        binding.banner.addBannerLifecycleObserver(viewLifecycleOwner)
        binding.rvType.layoutManager = LinearLayoutManager(requireContext()).apply { orientation = RecyclerView.HORIZONTAL }
        binding.viewPager.isUserInputEnabled = false
    }

    override fun initEvent() {
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            if (selectType == position) return@setOnItemClickListener
            if (!UserUtil.isLogin()) {
                startActivity(Intent(requireActivity(), LoginActivity::class.java))
                return@setOnItemClickListener
            }
            selectType = position
            typeAdapter.notifyDataSetChanged()
            binding.viewPager.setCurrentItem(position, false)
        }
        binding.appBar.addOnOffsetChangedListener { _, verticalOffset ->
            var alpha = if (scrollHeight <= 0) 0f else abs(verticalOffset).toFloat() / scrollHeight
            alpha = DecelerateInterpolator().getInterpolation(if (alpha > 1) 1f else if (alpha < 0) 0f else alpha)
            binding.rlHeader.isInvisible = alpha <= 0
            binding.rlHeader.alpha = alpha
            binding.clHeader.alpha = 1 - alpha
            binding.llBg1.alpha = 1 - alpha
            binding.llBg2.alpha = alpha
        }
        binding.ivTerms.setOnClickListener {
            startActivity(Intent(requireActivity(), TermsActivity::class.java))
        }
        binding.clHeader.setOnClickListener(this)
        binding.btnApply.setOnClickListener(this)
        binding.btnApplyTop.setOnClickListener(this)
    }

    private var recommend: Recommend? = null

    override fun initData() {
        getConfig {
            if (UserUtil.isLogin()) {
                http {
                    val map = getHttpMap(501)
                    val userInfo = request<UserInfo>(map, ApiService.path4)
                    if (!userInfo?.name.isNullOrEmpty()) {
                        binding.tvHello.text = getString(R.string.hello) + userInfo!!.name + "!"
                    } else {
                        binding.tvHello.text = getString(R.string.hello) + it.helloUserName + "!"
                    }
                }
            } else {
                binding.tvHello.text = getString(R.string.hello) + it.helloUserName
            }
            binding.ivHead.load(it.logoUrl) {
                placeholder(R.mipmap.icon_round)
                error(R.mipmap.icon_round)
            }
            binding.tvWelcome.text = it.welcomeWord
            if (!it.motivePromotions.isNullOrEmpty()) {
                binding.banner.setAdapter(NoticeAdapter(requireActivity(), it.motivePromotions))
            }
        }
        http {
            val map = getHttpMap(203)
            val list = request<List<Recommend>>(map, ApiService.path2)
            if (list.isNullOrEmpty()) return@http
            list[0].let {
                recommend = it
                binding.ivIcon.load(it.productLogoUrl)
                binding.tvName.text = it.productName
                binding.ivHot.load(it.fireBasePicture)
                binding.tvHot.text = it.recommendWord
                if (it.currency.isNotEmpty()) {
                    binding.tvMax.text = getString(R.string.maximum_amount) + " (" + it.currency + ")"
                    binding.tvMaxTitle.text = getString(R.string.maximum_amount) + " (" + it.currency + ")"
                }
                binding.tvAmount.text = it.maxAmount.formatAmount()
                binding.tvAmountTitle.text = it.maxAmount.formatAmount()
                binding.ivDes1.load(it.featureOneUrl)
                binding.tvDes1.text = it.featureOneDesc
                binding.ivDes2.load(it.featureTwoUrl)
                binding.tvDes2.text = it.featureTwoDesc
            }
        }
        http {
            val map = getHttpMap(103)
            val list = request<List<Type>>(map, ApiService.path5) ?: listOf()
            selectType = 0
            types.clear()
            types.addAll(list)
            typeAdapter.submitList(types)
            typeAdapter.notifyDataSetChanged()
            binding.viewPager.offscreenPageLimit = if (types.size <= 0) 1 else types.size
            binding.viewPager.adapter = object : FragmentStateAdapter(this@HomeFragment) {
                override fun getItemCount(): Int {
                    return types.size
                }

                override fun createFragment(position: Int): Fragment {
                    val fragment = ProductFragment()
                    fragment.arguments = bundleOf(
                        "index" to position,
                        "type" to types[position].queryKey
                    )
                    return fragment
                }
            }
            binding.viewPager.setCurrentItem(0, false)
        }
    }

    override fun onClick(v: View) {
        if (!UserUtil.isLogin()) {
            startActivity(Intent(requireActivity(), LoginActivity::class.java))
            return
        }
        when (v) {
            binding.btnApplyTop, binding.btnApply -> {
                if (recommend == null) return
                http(onFinish = ::dismissLoading) {
                    showLoading()
                    val map = getHttpMap(206)
                    map["productId"] = recommend?.productId
                    request<Any>(map, ApiService.path3)
                    requireActivity().jump(recommend?.clickUrl, recommend?.productId)
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun login(loginEvent: LoginEvent) {
        initData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun logout(logoutEvent: LogoutEvent) {
        initData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun save(saveInfoEvent: SaveInfoEvent) {
        if (saveInfoEvent.name.isNotEmpty()) {
            binding.tvHello.text = getString(R.string.hello) + saveInfoEvent.name + "!"
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

}